package com.junmo.oauth.module.system.controller;


import com.junmo.oauth.module.system.entity.SysRole;
import com.junmo.oauth.module.system.service.SysRoleService;
import com.junmo.oauth.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
@Slf4j
public class SysRoleController {
    @Autowired
    SysRoleService sysRoleService;

    @GetMapping("/findAll")
    public R findAll(){
        return R.success("success",sysRoleService.findAll());
    }

    @GetMapping("/page")
    public R page(SysRole search, Integer currentPage, Integer pageSize,
                  @RequestParam(defaultValue = "roleCode") String sortField, @RequestParam(defaultValue = "asc")String sortOrder){
        Sort.Direction direction= sortOrder.toLowerCase().contains("asc")?Sort.Direction.ASC:Sort.Direction.DESC;
        Pageable pageable = PageRequest.of(currentPage - 1, pageSize,Sort.by(direction,sortField));
        Page<SysRole> page =  sysRoleService.page( search, pageable);
        return R.success(page);
    }

    @PostMapping()
    public R create(@RequestBody SysRole entity){
        return  sysRoleService.create( entity);
    }

    @PutMapping()
    public R edit(@RequestBody SysRole entity){
        return  sysRoleService.edit( entity);
    }

    @DeleteMapping()
    public R deleteByIds(@RequestBody List<Number> ids){
        return  sysRoleService.deleteByIds( ids);
    }
    @PostMapping("/assignResource/{roleId}")
    public R assignRole(@PathVariable("roleId") Number roleId ,@RequestBody List<Number> resourceIds){
        return  sysRoleService.assignResource( roleId,resourceIds);
    }
}
